package com.nike.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.nike.enums.AttributeType;
import com.nike.enums.WeightUnit;
import com.nike.model.Brand;
import com.nike.model.Product;
import com.nike.model.Productattribute;
import com.nike.model.Productcategory;
import com.nike.model.Producttype;
import com.nike.router.RouterMapping;
import com.nike.utils.AttachmentUtils;
import com.nike.utils.SerialNumberUtil;
import com.nike.utils.StringUtils;
/**
 * 商品列表
 * 
 * @author wuhantao
 *
 */
@RouterMapping(url = "/product", viewPath = "/view/product")
public class ProductController extends BaseController<Product> {

	// 列表
	public void index() {
		String pageNumber = getPara("pageNumber");
		// 如果pageNumber为空，就默认为第1页
		if (!StringUtils.isNotBlank(pageNumber)) {
			pageNumber = "1";
		}
		Page<Product> page = Product.DAO.doPaginate(StringUtils.toInt(pageNumber, 1), 10);
		setAttr("page", page);
		render("list.html");
	}

	public void toAdd() {
		setAttr("productCategoryTreeList", getProductCategoryTreeList());
		setAttr("allBrand", getAllBrand());
		setAttr("allWeightUnit", getAllWeightUnit());
		setAttr("allProductType", getAllProductType());

		render("add.html");
	}

	// 添加产品
	public void insert() throws Exception {
		Map<String, String> productAttributeMap = new HashMap<String, String>();
		// 获得产品
		Product product = getModel(Product.class, "product");
		// 商品重量
		String weightUnit = getPara("weightUnit", "");
		if (StringUtils.isNotBlank(weightUnit)) {
			product.set("weightUnit", WeightUnit.valueOf(weightUnit).ordinal());
		}
		if (product.getBigDecimal("price").compareTo(new BigDecimal("0")) < 0) {
			addActionError("销售价不允许小于0");
			return;
		}
		if (product.getBigDecimal("marketPrice").compareTo(new BigDecimal("0")) < 0) {
			addActionError("市场价不允许小于0");
			return;
		}
		if (product.getDouble("weight") < 0) {
			addActionError("商品重量只允许为正数或零!");
			return;
		}
		if (StringUtils.isNotEmpty(product.getStr("productSn"))) {
			if (Product.DAO.isExist(product.getStr("productSn"))) {
				addActionError("货号重复,请重新输入!");
				return;
			}
		} else {
			String productSn = SerialNumberUtil.buildProductSn();
			product.set("productSn", productSn);
		}
		// 积分
		// *******************
		// *********************
		if (StringUtils.isNotBlank(product.getStr("productType_id"))) {
			List<Productattribute> enabledProductAttributeList = Productattribute.DAO.getEnabledProductAttributeList(product
					.getProducttypeId());
			for (Productattribute productAttribute : enabledProductAttributeList) {
				String productAttributeId = productAttribute.getId().toString();
				AttributeType attributeType = AttributeType.valueOf(productAttribute.getAttributeType());
				if (attributeType == AttributeType.radio || attributeType == AttributeType.checkbox) {
					String[] attributeOptionList = getParaValues(productAttributeId);
					List<String> list = new ArrayList<String>();
					for (String optionList : attributeOptionList) {
						list.add(optionList);
					}
					ObjectMapper mapper = new ObjectMapper();
					// list转JSON
					String value = mapper.writeValueAsString(list);
					productAttributeMap.put(productAttributeId, value);

				} else {
					String value = getPara(productAttributeId);
					productAttributeMap.put(productAttributeId, value);
				}
			}
		}
		// 保存
		saved(product);
		// 保存产品属性
		if (productAttributeMap != null && productAttributeMap.size() > 0) {
			product.setProductAttributeMapStore(productAttributeMap);
		}
		// 重定向
		redirect("/product");
	}

	// 编辑
	public void toEdit() {
		String id = getPara("id");
		if (StringUtils.isNotBlank(id)) {
			setAttr("product", Product.DAO.findById(id));
		}
		setAttr("productCategoryTreeList", getProductCategoryTreeList());
		setAttr("allBrand", getAllBrand());
		setAttr("allWeightUnit", getAllWeightUnit());
		setAttr("allProductType", getAllProductType());

		render("add.html");
	}
	// 获取所有商品类型
	public List<Producttype> getAllProductType() {
		return Producttype.DAO.doFind();
	}

	// 获取所有品牌
	public List<Brand> getAllBrand() {
		return Brand.DAO.doFind();
	}

	// 获取商品分类树
	public List<Productcategory> getProductCategoryTreeList() {
		return Productcategory.DAO.getAll();
	}

	// 获取所有重量单位
	public Map<String, String> getAllWeightUnit() {

		Map<String, String> allWeightUnit = new TreeMap<String, String>();
		for (WeightUnit weightUnit : WeightUnit.values()) {
			allWeightUnit.put(weightUnit.getCode(), weightUnit.getRemark());
		}
		return allWeightUnit;
	}

	// 富文本上传文件返回展示
	public void upload() {
		UploadFile uploadFile = getFile();
		String url=AttachmentUtils.moveFile(uploadFile);
		List<String> imageurl = new ArrayList<String>();
		String imagesrc = "http://localhost:8093/upload/" + uploadFile.getFileName();
		renderText(url);
		imageurl.add(imagesrc);
		setAttr("imagelist", url);
	}

	public void test() {
		render("updateImage.html");
	}

}
